<template>
    <div>
       <layout-box one="商品管理" two="分类参数">
           <!-- 警告区域 -->
           <el-alert
               title="注意：只允许为第三级分类设置相关参数"
               type="warning"
               show-icon
               >
            </el-alert>
            <!-- 选择商品分类区域 -->
            <el-row class="cate_opt">
                <el-col>
                    <span>选择商品分类：</span>
                    <!-- 选择商品分类的级联 -->
                    <el-cascader
                        v-model="selectedCateKeys"
                        :options="cateList"
                        :props="cateProps"
                        @change="handleChange">
                    </el-cascader>
                </el-col>
            </el-row>
            <!-- tab页标签区域 -->
            <el-tabs v-model="activeName" @tab-click="handleClick">
                <el-tab-pane label="动态参数" name="many">
                    <!-- 动态参数面板 -->
                    <el-button type="primary" size="mini" :disabled="isButtonDisabled"  @click="addDialogVisible=true">添加参数</el-button>
                    <!--动态参数列表 -->
                    <el-table :data="manyTableData" border stripe>
                        <!-- 展开列 -->
                        <el-table-column type="expand">
                            <template slot-scope="scope">
                                <!-- {{scope.row}} -->
                                <!-- 循环渲染tag标签 -->
                                 <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i" closable @close="handleClose(scope.row,i)">{{item}}</el-tag>
                                <el-input
                                    class="input-new-tag"
                                    v-if="scope.row.inputVisible"
                                    v-model="scope.row.inputValue"
                                    ref="saveTagInput"
                                    size="small"
                                    @keyup.enter.native="handleInputConfirm(scope.row)"
                                    @blur="handleInputConfirm(scope.row)"
                                >
                                </el-input>
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>

                            </template>
                        </el-table-column>
                        <!-- 索引 -->
                        <el-table-column type="index"></el-table-column>
                        <el-table-column label="参数名称" prop="attr_name"></el-table-column>
                        <el-table-column label="操作" >
                            <template slot-scope="scope">
                                <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEidtDialog(scope.row.attr_id)">编辑</el-button>
                                <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeParams(scope.row.attr_id)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
                <el-tab-pane label="静态属性" name="only">
                    <!-- 静态属性面板 -->
                    <el-button type="primary" size="mini" :disabled="isButtonDisabled" @click="addDialogVisible=true">添加属性</el-button>
                    <!-- 静态属性列表 -->
                    <el-table :data="onlyTableData" border stripe>
                        <!-- 展开列 -->
                        <el-table-column type="expand">
                             <template slot-scope="scope">
                                <!-- {{scope.row}} -->
                                <!-- 循环渲染tag标签 -->
                                 <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i" closable @close="handleClose(scope.row,i)">{{item}}</el-tag>
                                <el-input
                                    class="input-new-tag"
                                    v-if="scope.row.inputVisible"
                                    v-model="scope.row.inputValue"
                                    ref="saveTagInput"
                                    size="small"
                                    @keyup.enter.native="handleInputConfirm(scope.row)"
                                    @blur="handleInputConfirm(scope.row)"
                                >
                                </el-input>
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>

                            </template>
                        </el-table-column>
                        <!-- 索引 -->
                        <el-table-column type="index"></el-table-column>
                        <el-table-column label="参数名称" prop="attr_name"></el-table-column>
                        <el-table-column label="操作" >
                            <template slot-scope="scope">
                                <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEidtDialog(scope.row.attr_id)">修改</el-button>
                                <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeParams(scope.row.attr_id)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>
       </layout-box>
       <!-- 添加对话框 -->
       <el-dialog
            :title="'添加'+titleText"
            :visible.sync="addDialogVisible"
            width="50%"
            @close="closeAddFormDialog"
            >
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" >
                <el-form-item :label="titleText" prop="attr_name">
                    <el-input v-model="addForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="addDialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="addParams">确 定</el-button>
            </span>
       </el-dialog>
       <!-- 修改对话框 -->
        <el-dialog
            :title="'修改'+titleText"
            :visible.sync="editDialogVisible"
            width="50%"
            @close="closeeditFormDialog"
            >
            <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px" >
                <el-form-item :label="titleText" prop="attr_name">
                    <el-input v-model="editForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="editDialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="editParams">确 定</el-button>
            </span>
       </el-dialog>
    </div>
</template>
<script>
export default {
    data(){
        return {
            cateList:[],
            cateProps:{
                value:'cat_id',
                label:'cat_name',
                children:'children',
                expandTrigger: 'hover',
            },
            // 级联选择器选中项变化，会触发这个函数
            selectedCateKeys:[],
            // 标签页的选中项
            activeName:'many',
            // 动态参数数据
            manyTableData:[],
            // 静态属性数据
            onlyTableData:[],
            addDialogVisible:false,
            addForm:{
                attr_name:'',

            },
            // 添加参数验证规则对象
            addFormRules:{
                attr_name:[
                {required:true,message: '请输入参数名称', trigger: 'blur'}
               ]
            },
            editDialogVisible:false,
            // 修改参数验证规则对象
            editFormRules:{
                attr_name:[
                {required:true,message: '请输入参数名称', trigger: 'blur'}
               ]
            },
            // 编辑表单对象
            editForm:{
                 attr_name:'',
                  attr_id:null,
                  attr_sel:''
            },
        }
    },
    created(){
        // 获取商品分类数据
        this.getCateList()
    },
    computed: {
        isButtonDisabled(){
            if(this.selectedCateKeys.length===3){
                return false
            }else{
                return true
            }
        },
        cateId(){
            if(this.selectedCateKeys.length===3){
                return this.selectedCateKeys[2]
            }else{
                return null
            }
        },
        titleText(){
            if(this.activeName==='many'){
                return '动态参数'
            }else{
                return '静态属性'
            }
        }
    },
    
    methods:{
        async getCateList(){
            const {data:res}=await this.$http.get('categories')
            // console.log(res);
            if(res.meta.status!==200) return this.$message.error('获取分类数据失败')
            // this.$message.success('获取分类数据成功')
            this.cateList=res.data
            console.log(this.cateList); 
        },
        // 级联选择器选中项会触发这个函数
        handleChange(){
            this.getParamsData()
        },
        // tab页标签选中项的处理函数
        handleClick(){
            console.log(this.activeName);
            this.getParamsData()
        },
        // 获取参数列表的处理函数
        async getParamsData(){
            // 判断选中的是否为三级分类
            if(this.selectedCateKeys.length!==3){
                this.selectedCateKeys=[]
                this.manyTableData=[]
                this.onlyTableData=[]
                return
            }
            console.log(this.selectedCateKeys); 
            // console.log(this.cateId);
            // 获取参数列表
            const {data:res}=await this.$http.get(`categories/${this.cateId}/attributes`,
            {params:{sel:this.activeName}}) 
            // console.log(res);
            if(res.meta.status!==200) return this.$message.error('获取参数列表失败')
            //  this.$message.success('获取参数列表成功')
            console.log(res.data);
            res.data.forEach(item=>{
                // 判断item.attr_vals是否为空
                item.attr_vals=item.attr_vals?item.attr_vals.split(','):[]//以空格分割
                item.inputVisible=false
                item.inputValue=''

            })
            console.log(res.data);
            if(this.activeName==='many') {
                this.manyTableData=res.data
            }else{
                this.onlyTableData=res.data
            }
            
        },
        // 监听关闭添加对话框处理函数
        closeAddFormDialog(){
            this.$refs.addFormRef.resetFields()
        },
        // 添加参数
        addParams(){
            this.$refs.addFormRef.validate(async valid=>{
                // console.log(valid);
                if(!valid) return 
                const {data:res}=await this.$http.post(`categories/${this.cateId}/attributes`,{
                    attr_name:this.addForm.attr_name,
                    attr_sel:this.activeName,
                })
                // console.log(res); 
                if(res.meta.status!==201) return this.$message.error('添加参数失败')
                // this.$message.success('添加参数成功')
                this.addDialogVisible=false
                this.getParamsData()
            })
        },
        //  展示编辑对话框
        async showEidtDialog(attr_id){
            console.log(attr_id);
            const {data:res}=await this.$http.get(`categories/${this.cateId}/attributes/${attr_id}`,{
                params:{attr_sel:this.activeName}
            })
            console.log(res);
            if(res.meta.status!==200) return this.$message.error('根据id查询参数失败')
            this.editForm=res.data
            console.log(this.editForm);
            this.editDialogVisible=true
        },
        //监听关闭修改参数的对话框
        closeeditFormDialog(){
            this.$refs.editFormRef.resetFields()
        },
        // 编辑参数
         editParams(){
           this.$refs.editFormRef.validate(async valid=>{
            //    console.log(valid);
            if(!valid) return 
            const {data:res}=await this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`,{
                attr_name:this.editForm.attr_name,attr_sel:this.activeName
            })
            console.log(res);
            if(res.meta.status!==200) return this.$message.error('修改参数失败')
            // this.$message.success('修改参数成功')
            this.getParamsData()
            this.editDialogVisible=false
           })
         },
        //  删除参数
        async removeParams(attr_id){
            const confirmResult=await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err=>err)
            console.log(confirmResult);
            if(confirmResult!=='confirm')
            return this.$message('取消了删除该参数')
            // console.log(typeof this.cateId);
            const {data:res}=await this.$http.delete(`categories/${this.cateId}/attributes/${attr_id}`)
            // console.log(res);
            if(res.meta.status!==200) return this.$message.error('删除参数失败')
            this.getParamsData()
        },
        // 展示循环生成标签的文本框
        showInput(row){
            row.inputVisible=true
            // 当页面被重新渲染之后，才会指定回调函数中的代码
            this.$nextTick(_ => {
            this.$refs.saveTagInput.$refs.input.focus();
        });
        },
        // 失去焦点时触发,或按下enter键时都会触发
        handleInputConfirm(row){
            // console.log('ok');
            if(row.inputValue.trim().length===0){
                row.inputVisible=false
                row.inputValue=''
                return
            }
            // 如果没有return ,则证明输入了内容，需要做后续的处理
            // 将文本框输入的内容渲染出来
            row.attr_vals.push(row.inputValue)
            row.inputVisible=false
            row.inputValue=''
            // 从后台更新数据
           this.saveAttrVals(row);
        },
        // 将对attr_vals的操作保存到数据库
        async saveAttrVals(row){
            const {data:res}=await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,{
                attr_name:row.attr_name,
                attr_sel:this.activeName,
                attr_vals:row.attr_vals.join(',')
            })
            // console.log(res);
            if(res.meta.status!==200) return this.$message.error('修改参数项失败')
            this.$message.success('修改参数项成功')
        },
        // 监听关闭事件，删除对应的参数项
        handleClose(row,i){
            // 重新渲染了前端页面
            row.attr_vals.splice(i,1)
            // 修改数据，保存到数据库
            this.saveAttrVals(row)
        }
        
    }
}
</script>
<style lang="less" scoped>
    .cate_opt{
        margin:15px 0;
    }
    .el-tag{
        margin-right:15px;
    }
    .input-new-tag{
        width:200px
    }
</style>

